#!/bin/bash
# facelogclient 编译脚本(支持交叉编译)
# Optional Environment Variables: 
#        TOOLCHAIN_FILE 指定交叉编译的工具链文件
# 		 MACHINE 目标平台, such as x86_64-linux-gnu,默认使用当前系统平台
#        PREFIX 安装路径
#        THRIFT_HOME thrift 库安装路径
#        PROJECT_FOLDER cmake 生成的工程文件(Makefile)文件夹
#        BUILD_TYPE 编译版本类型(DEBUG|RELEASE),默认 DEBUG
#		 BOOST_ROOT 指定 boost 库的安装位置,默认使用系统安装路径
# 		 ERPC_HOME 指定 erpc 库的安装位置
#		 RELEASE_PRJ 为 ON 时编译并 release 版本
# 安装对应平台的依赖库
# sudo apt-get install g++ gcc libboost-all-dev libssl-dev

sh_folder=$(dirname $(readlink -f $0))
folder_name=$(basename $sh_folder) 
# 定义编译的版本类型(DEBUG|RELEASE)
build_type=DEBUG
[[ "${BUILD_TYPE^^}" =~ DEBUG|RELEASE ]] && build_type=${BUILD_TYPE^^}

echo build_type=$build_type

machine=$(g++ -dumpmachine)

[ -n "$MACHINE" ] && machine=$MACHINE

toolchain=
[ -n "$TOOLCHAIN_FILE" ] && toolchain="-DCMAKE_TOOLCHAIN_FILE=$TOOLCHAIN_FILE"

[ -n "$PREFIX" ] && install_prefix="$PREFIX"
[ -z "$PREFIX" ] && install_prefix=$sh_folder/release/facelogclient_$machine
[ -e "$install_prefix" ] && rm -fr "$install_prefix"

[ -n "$PROJECT_FOLDER" ] && prj_folder="$PROJECT_FOLDER"
[ -z "$PROJECT_FOLDER" ] && prj_folder=$sh_folder/../$folder_name.gnu

boost_root=
[ -n "$BOOST_ROOT" ] && boost_root="-DBOOST_ROOT=$BOOST_ROOT"
[ -n "$BOOST_ROOT" ] && [ ! -d "$BOOST_ROOT" ] && echo "INVALID BOOST_ROOT=$BOOST_ROOT" && exit 255

thrift_home=$sh_folder/dependencies/dist/thrift-$machine
[ -n "$THRIFT_HOME" ] && thrift_home="$THRIFT_HOME"
[ -n "$THRIFT_HOME" ] && [ ! -d "$THRIFT_HOME" ] && echo "INVALID THRIFT_HOME=$THRIFT_HOME" && exit 255

erpc_home=$sh_folder/dependencies/release/erpc-$machine
[ -n "$ERPC_HOME" ] && erpc_home="$ERPC_HOME"
[ -n "$ERPC_HOME" ] && [ ! -d "$ERPC_HOME" ] && echo "INVALID ERPC_HOME=$ERPC_HOME" && exit 255

pushd $sh_folder/..

[ -d $prj_folder ] && rm -fr $prj_folder
mkdir -p $prj_folder || exit 255

pushd $prj_folder
echo "creating $(arch) Project for gnu ..."
cmake "$sh_folder" -G "Eclipse CDT4 - Unix Makefiles" -DCMAKE_BUILD_TYPE=$build_type \
	-DCMAKE_INSTALL_PREFIX=$install_prefix \
	-DTHRIFT_HOME=$thrift_home \
	-DCMAKE_PREFIX_PATH=$erpc_home \
	-DBoost_USE_STATIC_LIBS=ON \
	-DBoost_USE_STATIC_RUNTIME=ON  \
  	$boost_root $toolchain || exit 255

	#-DBOOST_ROOT=$sh_folder/dependencies/dist/boost_$machine 

if [[ "${RELEASE_PRJ^^}" =~ ON ]]
then
	cmake --build . --target clean || exit 255
	cmake --build . --target install -- -j8 || exit 255
	echo "==============copy proxy executable file=================="
	mkdir -p $sh_folder/proxy/$machine || exit 255
	cp -fv  $install_prefix/bin/erpc_proxy \
			$install_prefix/bin/erpc_proxy_mini \
			$sh_folder/proxy/$machine
fi

popd
popd

